/*
 *
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */

package com.qingyan.flink.core.sink;

import cn.hutool.json.JSONUtil;
import com.qingyan.flink.core.Table;
import com.qingyan.flink.core.properties.FlinkDataSourceProperties;
import org.apache.commons.lang3.StringUtils;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.java.typeutils.RowTypeInfo;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.data.RowData;
import org.apache.flink.table.types.logical.*;
import org.apache.flink.table.types.utils.TypeConversions;
import org.apache.flink.types.Row;
import org.apache.flink.types.RowKind;
import org.apache.flink.util.Collector;

import java.io.Serializable;
import java.time.ZoneId;
import java.util.*;

/**
 * SQLSinkBuilder
 *
 * @author wenmo
 * @since 2022/4/25 23:02
 */
public class SQLSinkBuilder extends AbstractSinkBuilder implements Serializable {

    public static final String KEY_WORD = "sql";
    private static final long serialVersionUID = -3699685106324048226L;
    private ZoneId sinkTimeZone = ZoneId.of("UTC");


    public SQLSinkBuilder(FlinkDataSourceProperties sinkProperties, Map<String, String> sinkConfig) {
        super(sinkProperties, sinkConfig);
    }

    private DataStream<Row> buildRow(
            DataStream<Map> filterOperator,
            List<String> columnNameList,
            List<LogicalType> columnTypeList,
            String schemaTableName) {
        final String[] columnNames = columnNameList.toArray(new String[columnNameList.size()]);
        final LogicalType[] columnTypes = columnTypeList.toArray(new LogicalType[columnTypeList.size()]);
        TypeInformation<?>[] typeInformations = TypeConversions.fromDataTypeToLegacyInfo(TypeConversions.fromLogicalToDataType(columnTypes));
        RowTypeInfo rowTypeInfo = new RowTypeInfo(typeInformations, columnNames);
        return filterOperator
                .flatMap(new FlatMapFunction<Map, Row>() {
                    @Override
                    public void flatMap(Map value, Collector<Row> out) throws Exception {
                        try {
                            switch (value.get("op").toString()) {
                                case "r":
                                case "c":
                                    Row irow = Row.withPositions(RowKind.INSERT, columnNameList.size());
                                    Map idata = (Map) value.get("after");
                                    for (int i = 0; i < columnNameList.size(); i++) {
                                        irow.setField(i,
                                                convertValue(idata.get(columnNameList.get(i)), columnTypeList.get(i)));
                                    }
                                    out.collect(irow);
                                    break;
                                case "d":
                                    Row drow = Row.withPositions(RowKind.DELETE, columnNameList.size());
                                    Map ddata = (Map) value.get("before");
                                    for (int i = 0; i < columnNameList.size(); i++) {
                                        drow.setField(i,
                                                convertValue(ddata.get(columnNameList.get(i)), columnTypeList.get(i)));
                                    }
                                    out.collect(drow);
                                    break;
                                case "u":
                                    Row ubrow = Row.withPositions(RowKind.UPDATE_BEFORE, columnNameList.size());
                                    Map ubdata = (Map) value.get("before");
                                    for (int i = 0; i < columnNameList.size(); i++) {
                                        ubrow.setField(i,
                                                convertValue(ubdata.get(columnNameList.get(i)), columnTypeList.get(i)));
                                    }
                                    out.collect(ubrow);
                                    Row uarow = Row.withPositions(RowKind.UPDATE_AFTER, columnNameList.size());
                                    Map uadata = (Map) value.get("after");
                                    for (int i = 0; i < columnNameList.size(); i++) {
                                        uarow.setField(i,
                                                convertValue(uadata.get(columnNameList.get(i)), columnTypeList.get(i)));
                                    }
                                    out.collect(uarow);
                                    break;
                                default:
                            }
                        } catch (Exception e) {
                            logger.error("SchameTable: {} - Row: {} - Exception:", schemaTableName,
                                    JSONUtil.toJsonStr(value), e);
                            throw e;
                        }
                    }
                }, rowTypeInfo);
    }

    @Override
    public String getHandle() {
        return KEY_WORD;
    }


    @Override
    public SinkBuilder create(FlinkDataSourceProperties properties, Map<String, String> sourceConfig) {
        return null;
    }


    @Override
    public String getSinkSchemaName(Table table) {
        return null;
    }

    @Override
    public String getSinkTableName(Table table) {
        return null;
    }

    @Override
    public void addSink(StreamExecutionEnvironment env, StreamTableEnvironment tableEnv, DataStream<RowData> rowDataDataStream, Table table, List<String> columnNameList, List<LogicalType> columnTypeList) {

    }
}
